package ru.home.requests;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetRequest {
		
	public String getRequestInterface(String url) throws Exception {
		String result = getRequest(url);
		return result;
	}
	
	public String postRequestInterface(String url, String params) throws Exception {
		String result = postRequest(url, params);
		return result;
	}
	
	private String postRequest(String url, String params) throws Exception {
		String result = null;
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		
		con.setRequestMethod("POST");
		
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(params);
		wr.flush();
		wr.close();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		
		in.close();
		
		result += response;
		
		return result;		
	}
	
	private String getRequest(String url) throws Exception {
		String result = null;
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		
		con.setRequestMethod("GET");
		
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		
		while ((inputLine = in.readLine()) != null) {
			
			response.append(inputLine);
			
		}
		
		in.close();
		
		result += response;
		
		return result;				
		
	}

}
